import { defineNuxtPlugin, useRuntimeConfig } from "#app";
import type { CSSProperties } from "@vue/runtime-dom";
import { useGlobalStore } from "~~/store/global";
import { useEventBus } from "@vueuse/core";
import { loadScript } from "@/utils";

/**
 * 测试/生产环境下增加切换语言环境的插件
 */
export default defineNuxtPlugin((app) => {
  const globalStore = useGlobalStore();
  const whiteList = ["dev", "test", "prep"];
  const { WEB_NODE_ENV = "prod" } = useRuntimeConfig().public;
  const showToastEmit = useEventBus("showToast-emit");
  const showDebuggerEmit = useEventBus("show-debugger-emit");

  if (whiteList.includes(WEB_NODE_ENV) && process.client) {
    const body = document.body;
    const ul = document.createElement("ul");
    // 英语、印度英文、菲律宾 翻译是一样的
    const locals = {
      en: "英语",
      in_en: "印度英文",
      ph: "菲律宾",
      indonesia: "印尼",
      mys: "马来西亚",
      pt: "葡萄牙",
      VI: "越南",
      zh_hk: "中文繁体",
      debugger: "调试",
      close: "关闭切换",
    } as const;

    const ulStyles: CSSProperties = {
      position: "fixed",
      right: "0",
      top: "50%",
      transform: "translateY(-50%)",
      color: "green",
      zIndex: 9999,
    };

    const liStyles: CSSProperties = {
      border: "1px solid black",
      padding: "5px 8px",
      textAlign: "center",
    };

    const addStyle = (el: HTMLElement, styles: CSSProperties) => {
      for (const attr in styles) {
        // @ts-ignore
        if (el.style) el.style[attr] = styles[attr];
      }
    };

    type Local = keyof typeof locals;
    for (const local in locals) {
      const label = locals[local as Local];
      const li = document.createElement("li");
      addStyle(li, liStyles);
      li.innerHTML = label;
      ul.appendChild(li);
    }

    addStyle(ul, ulStyles);

    ul.addEventListener("click", (e) => {
      const li = e.target as HTMLLIElement;
      const label = li.innerHTML;
      const local = Object.entries(locals).find(
        ([key, value]) => value === label
      )![0];

      if (local) {
        if (local === "close") {
          body.removeChild(ul); // 手动移除翻译切换
        } else if (local === "debugger") {
          // 1. 打开调试模式
          if (!window.VConsole) {
            loadScript("/vconsole.min.js", () => {
              new VConsole();
            });
          }
          // 2. 发送调试信息
          const token =globalStore.$state.token;
          showDebuggerEmit.emit(token);
        } else {
         globalStore.$patch((state) => {
            state.language = local ?? "en";
          });
        }
        // showToastEmit.emit("mvp.other.text12"); // 成功
      }
    });

    body.appendChild(ul);
  }
});
